﻿using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Web.Hosting;
using System.Web.UI;
using Microsoft.SharePoint;
using OS.Infrastructure.Common;
using TaskKernel.BootStrapper;
using TaskKernel.Domain;
using TaskWebApplicationUI.PresenterLayer;
using log4net;
using log4net.Config;

namespace TaskWebApplicationUI
{
    public interface IAbstractView
    {
        string LogonUser { get; }
        string WebPath { get; }
        string DepartmentName { set; }
    }

    public abstract class ViewPage<TView, TPresenter>
        : Page
        where TPresenter : AbstractPresenter<TView>
        where TView : class, IAbstractView
    {
        private string _logonUser;
        protected CookieHelper CookieHelper;
        protected long MaxFileSize;
        private readonly bool _isSharepoint;

        protected ViewPage()
        {
            bool.TryParse(ConfigurationManager.AppSettings["isSharepoint"], out _isSharepoint);
        }


        public TPresenter Presenter { get; set; }

        public string LogonUser
        {
            get { return _logonUser; }
        }

        public string WebPath
        {
            get { return _isSharepoint ? GetSharepointBasePath() : GetBasePath(); }
        }

        private void Page_Error(object sender, EventArgs e)
        {
            var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            var currentWebRootFilePath = HostingEnvironment.ApplicationPhysicalPath;
            var relativePath = _isSharepoint ? Path.Combine(ConfigurationManager.AppSettings["appName"], ConfigurationManager.AppSettings["log4net"]) : ConfigurationManager.AppSettings["log4net"];
            var api4NetConfigPath = Path.Combine(currentWebRootFilePath, relativePath);
            XmlConfigurator.Configure(new FileInfo(api4NetConfigPath));
            // working only config in wwwroot\wss\VirtualDirectories\80
            log.Error(WebPath);
            log.Error(LogonUser);
            log.Error(Context.Error.Message);
            log.Error(Context.Error.StackTrace);
        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            Page.Error += Page_Error;
            if (!_isSharepoint) return;
            var sharepointMasterpage = ConfigurationManager.AppSettings["sharepointMasterpage"];
            if (!string.IsNullOrEmpty(sharepointMasterpage))
                Page.MasterPageFile = sharepointMasterpage;
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            TaskKernelBootStrapper.Run(new WebAppAutoFacModule());
            CookieHelper = new CookieHelper(this);
            Presenter = IoC.Resolve<TPresenter>();
            Presenter.View = this as TView;
            _logonUser = Tools.DelDomain(WindowsIdentity.GetCurrent().Name).ToLower();
        }

        private string GetSharepointBasePath()
        {
            return SPContext.Current.Web.ServerRelativeUrl;
        }

        protected string GetBasePath()
        {
            var path = Request.Url.AbsolutePath;
            var index = path.LastIndexOf("/", System.StringComparison.Ordinal);
            var concatPath = path.Remove(index, path.Length - index);
            return concatPath;
        }
    }
}